using System;
using System.IO;
using System.Text;
using System.Xml;

namespace Greg.XmlEditor.Business.Concrete
{
	public class XmlValidator
	{
		private StringBuilder log;

		public XmlValidator()
		{
			this.Reset();
		}

		public bool Validate(string xmlString)
		{
			this.Reset();
			var result = false;
			try
			{
				using(var reader = XmlReader.Create(new StringReader(xmlString)))
				{
					while (reader.Read()) { }
					reader.Close();
				}

				this.log.Append("Document sintax check successful!");

				result = true;
			}
			catch (XmlException ex)
			{
				this.LogError(ex.Message);
			}

			return result;
		}

		public bool Validate(string xmlString, string xmlSchemaPath)
		{
			this.Reset();
			var result = false;
			try
			{
				var settings = new XmlReaderSettings();
				settings.Schemas.Add("", xmlSchemaPath);
				settings.ValidationType = ValidationType.Schema;

				using(var reader = XmlReader.Create(new StringReader(xmlString), settings))
				{
					while (reader.Read()) { }
					reader.Close();
				}


				log.Append("Document sintax check successful!");

				result = true;
			}
			catch (Exception ex)
			{
				this.LogError(ex.Message);
			}

			return result;
		}

		public string ValidationResult
		{
			get { return log.ToString(); }
		}

		private void Reset()
		{
			log = new StringBuilder();
		}

		private void LogError(string error)
		{
			log.Append(error);
			log.AppendLine();
		}
	}
}